# -*- coding:utf-8 -*-

import time
from rand_wait import RandWait
from playwright.sync_api import Playwright, sync_playwright, expect

import signal
import threading
from queue import Queue

class Tieba:
    def __init__(self, user_id, pwd) -> None:
        self.user_id = user_id
        self.pwd = pwd
        self.logined = False
        self.rand_wait = RandWait(1*10, 1*60) # 30-60分钟

        self.queue = Queue(2000)
        self.thread = threading.Thread(target=self.publish_fun)
        self.thread.start()
        self.stop_thread = False
        signal.signal(signal.SIGINT, self._exit_gracefully)
        signal.signal(signal.SIGTERM, self._exit_gracefully)

    def _exit_gracefully(self,signum, frame):
        print("开始退出线程")
        self.stop_thread = True
        
    def exit(self):
        print("主动退出线程")
        self.stop_thread = True

    # 登录
    def _login(self) -> None:
        try:
            self.browser = self.playwright.chromium.launch(headless=False)
            self.context = self.browser.new_context()
            self.page = self.context.new_page()
            self.page.goto("https://tieba.baidu.com/")
            self.page.get_by_role("link", name="登录", exact=True).click()
            self.page.get_by_text("用户名登录").click()
            self.page.get_by_placeholder("手机号/用户名/邮箱").click()
            time.sleep(1)
            self.page.get_by_placeholder("手机号/用户名/邮箱").fill(self.user_id)
            self.page.get_by_placeholder("手机号/用户名/邮箱").press("Tab")
            self.page.get_by_placeholder("密码").fill(self.pwd)
            self.page.get_by_role("button", name="登录").click()
            self.logined = True
            time.sleep(1)
        except:
            print('登录异常！')

    # 发布
    def _publish(self, tb_name ,title, text) -> None:
        self.rand_wait.wait()
        try:
            self.page.goto("https://tieba.baidu.com/f?kw=%s&fr=index" % tb_name)
            time.sleep(1)
            self.page.locator(".tbui_aside_float_bar > li:nth-child(3) > a").click()
            time.sleep(1)
            self.page.locator("input[name=\"title\"]").fill(title)
            self.page.locator("#ueditor_replace").fill(text)
            time.sleep(2)
            self.page.get_by_role("button", name="发 表").click()
        except:
            print('发布异常！')

    # 释放
    def _release_browser(self):
        if self.page:
            self.page.close()
            self.context.close()
            self.browser.close()

    # 发布
    def publish(self, class_name, title, text):
        self.queue.put([class_name, title, text])

    # 批量发布
    def publishs(self, publish_infos):
        for publish_info in publish_infos:
            self.queue.put(publish_info)
    
    def publish_fun(self):
        with sync_playwright() as self.playwright:
            self._login()
            while not self.stop_thread:
                publish_info = self.queue.get()
                self._publish(publish_info[0], publish_info[1], publish_info[2])
            self._release_browser()

if __name__ == '__main__':
    tieba = Tieba('18129835572', '')
    tieba.publishs([('阿里云盘', 'azzxxx', 'zzzxxx'), ('阿里云盘', 'azrfff', 'rrrfdff')])
